<?php
class IndexController extends Zend_Controller_Action {
	protected $_USER;

	public function init() {
		
		//* Initialize action controller here */
		$userMapper = new Application_Model_UserMapper();

		//Load user from cookie
		$myNamespace = new Zend_Session_Namespace('Dealscombined');
		try {
			$user = $userMapper -> authenticate();
			$this -> _USER = $user;
			$myNamespace -> user = serialize($user);
		} catch(Exception $e) {

			if (strpos($e -> getMessage(), 'Duplicate entry') !== false) {
				$this -> _helper -> FlashMessenger('We did something in the last request');
			}
			throw $e;
		}
		$this -> view -> keywords = array('Deals', 'Best Deals', 'Deals Combined', 'City Deals', 'Deal', 'London Deals');
		
		
		//Facebook connection
		$bootstrap = Zend_Controller_Front::getInstance() -> getParam('bootstrap');
		$options = $bootstrap -> getOptions();
		$config = array('appId' => $options['facebook']['appId'], 'secret' => $options['facebook']['appSecret']);
		$facebook = new Facebook_Facebook($config);

		// Get User ID
		$user = $facebook -> getUser();

		if ($user) {
			try {
				// Proceed knowing you have a logged in user who's authenticated.
				$user_profile = $facebook -> api('/me');
				$this->_USER->setUserProfile($user_profile);
			} catch (FacebookApiException $e) {
				error_log($e);
				$user = null;
			}
		}

		// Login or logout url will be needed depending on current user state.
		if ($user) {
			$this->_USER->setLogOutUrl($facebook -> getLogoutUrl());
		} else {
			$this->_USER->setLogInUrl($facebook -> getLoginUrl());
		}
		
		
		
	}

	public function indexAction() {
		// action body
		$dealMapper = new Application_Model_DealMapper();

		$userCity = $this -> _USER -> getCityId();
		$userCity = is_null($userCity) ? '34' : $userCity;

		$select = $dealMapper -> getDbTable() -> select();
		$select -> from(array('products' => 'products'), array('*', 'imageUrl' => 'products.merchant_image_url', 'random' => 'RAND()')) 
				-> where('image_url IS NOT NULL') 
				-> where('city_id = ?', (int)$userCity) 
				-> order('random')
				->limit(21); 

		$stmt = $select -> query();
		$result = $stmt -> fetchAll();
		$finalDeals = $result;

		//Fetch Max and Min prices
		$select = $dealMapper -> getDbTable() -> select();
		$select -> from(array('products' => 'products'), array('price', 'maxprice' => 'MAX(products.price)', 'minprice' => 'MIN(products.price)')) -> where('image_url IS NOT NULL');

		$stmt = $select -> query();
		$result = $stmt -> fetchAll();
		$prices = $result;

		if (!empty($finalDeals)) {
			$maxPrice = $prices[0]['maxprice'];
			$minPrice = $prices[0]['minprice']; 
		}

		//Fetch cities		
		$cityMapper = new Application_Model_CityMapper();
		$cities = $cityMapper -> fetchAll(null, 'name'); 
		$citiesArray = array();

		foreach ($cities as $city) {
			$citiesArray[] = $city -> toArray();
		}

		//Fetch Categories
		$categoryMapper = new Application_Model_CategoryMapper();
		$categories = $categoryMapper -> fetchAll();
		$categoriesArray = array();

		foreach ($categories as $category) {
			$categoriesArray[] = $category -> toArray();
		}
		$this -> view -> keywords = array('Deals', 'Best Deals', 'Deals Combined', 'City Deals', 'Deal', 'London Deals');
		$this -> view -> components = array('cities' => $citiesArray, 'deals' => $finalDeals, 'email' => $this -> _USER -> getEmail(), 'userCity' => $this -> _USER -> getCityId(), 'categories' => $categoriesArray, 'maxPrice' => $maxPrice, 'minPrice' => $minPrice);
	}

	public function updateUserData() {
		$this -> _helper -> layout() -> disableLayout();
		$this -> _helper -> viewRenderer -> setNoRender(true);

		$request = $this -> getRequest();
		if (!$request -> isGet()) {
			throw new Exception("Attributes no valid", 500);
		}
	}

	public function updateproductsAction() {
		$this -> _helper -> layout() -> disableLayout();
		$this -> _helper -> viewRenderer -> setNoRender(true);

		$request = $this -> getRequest();

		if (!$request -> isGet()) {
			throw new Exception("Attributes no valid", 500);
		}

		$newCity = $request -> getParam('city');

		if ($newCity) {
			$cityMapper = new Application_Model_CityMapper();
			$results = $cityMapper -> find($newCity);
			if ($results) {
				$userMapper = new Application_Model_UserMapper();
				$userMapper -> authenticate(null, $newCity);
				$this -> _redirect('/');
			}
		}
	}

}
